//
//  IntegralShopVC.swift
//  ShareUmbrella
//
//  Created by duanmingyang on 2017/9/13.
//  Copyright © 2017年 尧尚信息科技. All rights reserved.
//

import UIKit
import YSKit
import TSMessages

class IntegralShopVC: YSBaseViewController,UITableViewDelegate,UITableViewDataSource {
    
    let kScreenHeight = UIScreen.main.bounds.size.height
    let kScreenWidth = UIScreen.main.bounds.size.width
    var selfTableView:UITableView!
    var integralLab:UILabel!
    var dataArr = NSArray.init()
    var dataGoodname = NSMutableArray.init()
    var dataNeedPoint = NSMutableArray.init()
    var dataGoodId = NSMutableArray.init()
    var dataGoodPicture = NSMutableArray.init()
    var dic:NSDictionary!

    override func setup() {
        super.setup()
    }
    
    /*
     *
     * 界面布局初始化
     */
    override func buildUI() {
        super.buildUI()
        self.title = I18n("VC.LFSide.piontshop.titlte")
        
        self.addSelfTableView()
        self.getPointMainAciton()
        
    }
    
    //
    override func buildRx() {
        super.buildRx()
    }
    
    //RGB
    func RGB(r:CGFloat,_ g:CGFloat,_ b:CGFloat) -> UIColor{
        return UIColor(red: (r)/255.0, green: (g)/255.0, blue: (b)/255.0, alpha: 1.0)
    }
    
    //初始化背景颜色
    func initBackgourndViewColor() {
        self.view.backgroundColor = UIColor.white
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.integralLab.text = UserService.sharedInstance.point.value
    }
    
    //积分信息
    func getPointMainAciton(){
        HUD.show()
        _ = YSNetWorkManager.provider.requestJSON(YSStructTarget(UserAPI.getPointMainAciton(token: Auth.token))).subscribe(onNext: { [weak self] (data) in
            //
            HUD.hide()
            
            print(data)
            guard let `self` = self, let `data` = data else {
                return
            }
            
            self.dataArr = data["data"]["info"].arrayValue as NSArray
            //self.integralLab.text = data["data"]["point"].string ?? "0"
            print(data["data"]["point"].stringValue)
            UserService.sharedInstance.point.value = data["data"]["point"].stringValue
            self.integralLab.text = UserService.sharedInstance.point.value
            
            
            for index in 0...self.dataArr.count-1 {
                self.dataGoodname.add(data["data"]["info"][index]["goodName"].stringValue)
                self.dataNeedPoint.add(data["data"]["info"][index]["needPoint"].stringValue)
                self.dataGoodId.add(data["data"]["info"][index]["goodId"].stringValue)
                self.dataGoodPicture.add(data["data"]["info"][index]["goodPicture"].stringValue)
            }
            
            self.selfTableView.reloadData()
            
            }, onError: { [weak self](ErrorType) in
                HUD.hide()
                guard let  `self` = self else {
                    return
                }
                self.handle(withError: ErrorType)
        })
        
    }
    
    func getDictionaryFromJSONString(jsonString:String) ->NSArray{
        
        let jsonData:Data = jsonString.data(using: .utf8)!
        
        let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
        if dict != nil {
            return dict as! NSArray
        }
        return NSArray()
        
        
    }
    
    //添加一个tableview
    func addSelfTableView(){
        
        let v = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 180))
        v.backgroundColor = RGB(r: 0, 188, 113)
        
        let tv = UIView.init(frame: CGRect(x: 0, y: -1000, width: kScreenWidth, height: 1000))
        tv.backgroundColor = RGB(r: 0, 188, 113)
        v.addSubview(tv)
        
        let circul = UIView.init(frame: CGRect(x: (kScreenWidth-110)/2, y: (v.frame.size.height-130)/2, width: 110, height: 110))
        circul.layer.cornerRadius = 55
        circul.layer.borderWidth = 5
        circul.layer.borderColor = UIColor.white.cgColor
        circul.clipsToBounds = true;
        v.addSubview(circul)
        
        integralLab = UILabel.init()
        integralLab.backgroundColor = UIColor.clear;
        integralLab.frame = CGRect(x:0, y:0, width:110, height:110)
        integralLab.text = "0"
        integralLab.textColor = UIColor.white
        integralLab.font = UIFont.systemFont(ofSize: 40)
        integralLab.textAlignment = NSTextAlignment.center
        circul.addSubview(integralLab)
        
        let ll = UILabel.init()
        ll.backgroundColor = UIColor.clear;
        ll.frame = CGRect(x:0, y:150, width:kScreenWidth, height:20)
        ll.text = "您的可用积分"
        ll.textColor = UIColor.white
        ll.font = UIFont.systemFont(ofSize: 16)
        ll.textAlignment = NSTextAlignment.center
        v.addSubview(ll)
        
        selfTableView = UITableView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight-64), style: UITableViewStyle.plain)
        selfTableView.dataSource = self
        selfTableView.delegate = self
        selfTableView.backgroundColor = UIColor.clear
        selfTableView.separatorStyle = UITableViewCellSeparatorStyle.none;
        selfTableView.showsHorizontalScrollIndicator = false
        selfTableView.showsVerticalScrollIndicator = false
        selfTableView.tableHeaderView = v
        self.view.addSubview(selfTableView)
    }
    
    func switchSendOrderVC(_ button:UIButton){
        let index = button.tag
        let point = UserService.sharedInstance.point.value?.intValue()
        let vc = SendOrderVC.init()
        let gname = dataGoodname[index] as! String
        let gid = dataGoodId[index] as! String
        let npoint = dataNeedPoint[index] as! String
        vc.config(gname: gname, gid: gid, npoint: npoint)
        if(point!>0){
            self.ys.push(vc)
        }else{
            TSMessage.showNotification(withTitle: I18n("对不起，您的积分不够"), type: .error)
        }
        
    }
    
    //MARK:UITableView DataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataArr.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let iderntify:String = "swiftCell"
        var cell = tableView.dequeueReusableCell(withIdentifier: iderntify) as? IntegralShopCell
        if(cell == nil){
            cell=IntegralShopCell(style: UITableViewCellStyle.default
                , reuseIdentifier: iderntify);
            
        }
        let section = indexPath.section
//        let goodName = dataGoodname[section] as? String ?? ""
//        let needPoint = dataNeedPoint[section] as? String ?? ""
//
        
        let title = dataGoodname[section] as? String ?? ""
        let picture = dataGoodPicture[section] as? String ?? ""
        let needPoint = dataNeedPoint[section] as? String ?? ""
        
        cell?.setData(title: title, picture: picture, price: needPoint)
        
        cell?.shopCar?.tag = section
        cell?.shopCar?.addTarget(self, action: #selector(switchSendOrderVC(_:)), for: UIControlEvents.touchUpInside)
        
        return cell!
    }
    
    
    //MARK:UITableView Delegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selfTableView?.deselectRow(at: indexPath, animated: true)
        //print("你选中了\(indexPath)" )
        self.ys.push(GoodDetailVC())
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 110
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 20
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView.init(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 20))
        return view
    }


}
